package acn.spring.shop;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import acn.spring.domain.Item;
import acn.spring.service.ItemService;

@Controller
@RequestMapping("/item")
public class ItemController {
	
	@Autowired
	private ItemService itemService;
	
	private ModelAndView redirectShowAllItems() {
		return new ModelAndView(new RedirectView("/admin/item/showAllItemsController", true));
	}
	
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public ModelAndView showForm() {
		ModelAndView returned =  new ModelAndView();
		returned.setViewName("itemForm");
		
		Item item = new Item();
		
		returned.addObject("itemObject", item);
		return returned;
	}
	
	@RequestMapping(value={"/add", "/edit/{itemId}"}, method = RequestMethod.POST)
	public ModelAndView processForm(@ModelAttribute("itemObject") @Valid Item item, BindingResult result) {
		
		if(result.hasErrors()) {
			return new ModelAndView("itemForm");
		}
		
		if(item.getId() != 0) {
			itemService.deleteItem(item.getId());
			item.setId(0);
		}
		itemService.addItem(item);

		return redirectShowAllItems();
	}
	
	@RequestMapping(value="/showAllItemsJSON")
	public @ResponseBody List<Item> showAllItemsJSON() {
		
		List<Item> itemList = itemService.getAllItems();
		
		return itemList;
	}
	
	@RequestMapping(value="/showAllItemsController")
	public ModelAndView showAllItems() {
		ModelAndView returned =  new ModelAndView();
		returned.setViewName("showAllItems");
		
		List<Item> itemList = itemService.getAllItems();
		
		returned.addObject("itemList", itemList);
		return returned;
	}
	
	@RequestMapping(value="/edit/{itemId}", method=RequestMethod.GET)
	public ModelAndView showEditForm(@PathVariable Integer itemId) {
		
		ModelAndView returned =  new ModelAndView();
		returned.setViewName("itemForm");
		
		Item item = itemService.getItemWithId(itemId);
		
		returned.addObject("itemObject", item);
		return returned;
	}
	
	@RequestMapping(value="/delete/{itemId}", method=RequestMethod.GET)
	public ModelAndView delete(@PathVariable int itemId) {
		
		itemService.deleteItem(itemId);
		
		return redirectShowAllItems();
	}
	
}
